/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lu.manage.modular.system.controller;

import com.lu.manage.core.base.controller.BaseController;
import com.lu.manage.core.shiro.ShiroKit;
import com.lu.manage.core.tips.ErrorTip;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.StringUtil;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.model.server.utils.IpUtils;
import com.lu.manage.modular.system.service.SystemCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用控制器
 *
 * @author fengshuonan
 * @Date 2017年2月17日20:27:22
 */
@Controller
@RequestMapping("/system")
@Slf4j
public class SystemController extends BaseController {

//    @Autowired
//    private UserService userService;

    @Autowired
    private SystemCacheService systemCacheService;

//    @Autowired
//    private FileInfoService fileInfoService;
//
//    @Autowired
//    private NoticeService noticeService;

    /**
     * 控制台页面
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @GetMapping("/console")
    public String console() {
        return "/modular/frame/console.html";
    }

    /**
     * 分析页面
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @GetMapping("/console2")
    public String console2() {
        return "/modular/frame/console2.html";
    }

//    /**
//     * 跳转到首页通知
//     *
//     * @author fengshuonan
//     * @Date 2018/12/23 6:06 PM
//     */
//    @RequestMapping("/notice")
//    public String hello() {
//        List<Notice> notices = noticeService.list();
//        super.setAttr("noticeList", notices);
//        return "/modular/frame/notice.html";
//    }

    /**
     * 主页面
     *
     * @author fengshuonan
     * @Date 2019/1/24 3:38 PM
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "/modular/frame/welcome.html";
    }

    /**
     * 主题页面
     *
     * @author fengshuonan
     * @Date 2019/1/24 3:38 PM
     */
    @GetMapping("/theme")
    public String theme() {
        return "/modular/frame/theme.html";
    }

    /**
     * 跳转到修改密码界面
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @GetMapping("/user_chpwd")
    public String chPwd() {
        return "/modular/frame/password.html";
    }

    /**
     * 个人消息列表
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @GetMapping("/message")
    public String message() {
        return "/modular/frame/message.html";
    }

    /**
     * 通用树
     * @param formName
     * @param formId
     * @param treeUrl
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/commonTree")
    public Object commonTree(String formName, String formId, String treeUrl, Model model) throws Exception{
        if(ToolUtil.isOneEmpty(formName, formId, treeUrl)){
            throw new Exception("请求数据不完整");
        }
        try {
            model.addAttribute("formName", URLDecoder.decode(formName, "UTF-8"));
            model.addAttribute("formId", URLDecoder.decode(formId, "UTF-8"));
            model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("请求数据异常");
        }
        return "/common/tree_dlg.html";
    }

    /**
     * 排序树
     * @param isSort
     * @param nodes
     * @param treeUrl
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/treeSort")
    public String treeOrder(String isSort, String nodes, String treeUrl, Model model) throws Exception{
        if(ToolUtil.isOneEmpty(isSort, nodes, treeUrl)){
            throw new Exception("请求数据不完整");
        }
        try {
            model.addAttribute("isSort", URLDecoder.decode(isSort, "UTF-8"));
            model.addAttribute("nodes", URLDecoder.decode(nodes, "UTF-8"));
            model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("请求数据异常");
        }
        return "/common/tree_sort.html";
    }

    /**
     * 复选框树 父子联动
     * @param isCheck
     * @param ids
     * @param treeUrl
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/treeCheck")
    public String treeCheck(String isCheck, String ids, String treeUrl, Model model) throws Exception{
        if(ToolUtil.isOneEmpty(isCheck, ids, treeUrl)){
            throw new Exception("请求数据不完整");
        }
        try {
            model.addAttribute("isCheck", URLDecoder.decode(isCheck, "UTF-8"));
            model.addAttribute("ids", URLDecoder.decode(ids, "UTF-8"));
            model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("请求数据异常");
        }
        return "/common/tree_check.html";
    }

    /**
     * 复选框树 父子不联动
     * @param isCheck
     * @param ids
     * @param treeUrl
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/treeCheckNolinkage")
    public String treeCheckNolinkage(String isCheck, String ids, String treeUrl, Model model) throws Exception{
        if(ToolUtil.isOneEmpty(isCheck, ids, treeUrl)){
            throw new Exception("请求数据不完整");
        }
        try {
            model.addAttribute("isCheck", URLDecoder.decode(isCheck, "UTF-8"));
            model.addAttribute("ids", URLDecoder.decode(ids, "UTF-8"));
            model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("请求数据异常");
        }
        return "/common/tree_check_nolinkage.html";
    }

    /**
     * 通过服务器 解析获取 客户端ip
     * @param request
     * @return
     */
    @GetMapping("/getIp")
    @ResponseBody
    public Object getIp(HttpServletRequest request){
        String ip = IpUtils.getIpAddr(request);
        if(StringUtil.isNotEmpty(ip)){
            Map<String,Object> map = new HashMap<>();
            map.put("ip",ip);
            map.put("deptId", ShiroKit.getUser().getDeptId());
            return new SuccessTip(map);
        }
        return new ErrorTip(-1,"获取不到当前用户ip");
    }

    /**
     * 更新系统全局缓存
     * @return
     */
    @PostMapping("/updateGlobalCache")
    @ResponseBody
    public Object updateGlobalCache(){
        systemCacheService.init();
        return new SuccessTip();
    }

//    /**
//     * 跳转到查看用户详情页面
//     *
//     * @author fengshuonan
//     * @Date 2018/12/24 22:43
//     */
//    @RequestMapping("/user_info")
//    public String userInfo(Model model) {
//        Long userId = ShiroKit.getUserNotNull().getId();
//        User user = this.userService.getById(userId);
//
//        model.addAllAttributes(BeanUtil.beanToMap(user));
//        model.addAttribute("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));
//        model.addAttribute("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));
//        LogObjectHolder.me().set(user);
//        return "/modular/frame/user_info.html";
//    }
//
//    /**
//     * 通用的树列表选择器
//     *
//     * @author fengshuonan
//     * @Date 2018/12/23 6:59 PM
//     */
//    @RequestMapping("/commonTree")
//    public String deptTreeList(@RequestParam("formName") String formName,
//                               @RequestParam("formId") String formId,
//                               @RequestParam("treeUrl") String treeUrl, Model model) {
//
//        if (ToolUtil.isOneEmpty(formName, formId, treeUrl)) {
//            throw new RequestEmptyException("请求数据不完整！");
//        }
//
//        try {
//            model.addAttribute("formName", URLDecoder.decode(formName, "UTF-8"));
//            model.addAttribute("formId", URLDecoder.decode(formId, "UTF-8"));
//            model.addAttribute("treeUrl", URLDecoder.decode(treeUrl, "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            throw new RequestEmptyException("请求数据不完整！");
//        }
//
//        return "/common/tree_dlg.html";
//    }
//
//    /**
//     * 上传头像
//     *
//     * @author fengshuonan
//     * @Date 2018/11/9 12:45 PM
//     */
//    @RequestMapping("/uploadAvatar")
//    @ResponseBody
//    public Object uploadAvatar(@RequestParam String avatar) {
//
//        if (ToolUtil.isEmpty(avatar)) {
//            throw new RequestEmptyException("请求头像为空");
//        }
//
//        avatar = avatar.substring(avatar.indexOf(",") + 1);
//
//        fileInfoService.uploadAvatar(avatar);
//
//        return SUCCESS_TIP;
//    }
//
//    /**
//     * 预览头像
//     *
//     * @author fengshuonan
//     * @Date 2018/11/9 12:45 PM
//     */
//    @RequestMapping("/previewAvatar")
//    @ResponseBody
//    public Object previewAvatar(HttpServletResponse response) {
//
//        ShiroUser currentUser = ShiroKit.getUser();
//        if (currentUser == null) {
//            throw new ServiceException(CoreExceptionEnum.NO_CURRENT_USER);
//        }
//
//        //获取当前用户的头像id
//        User user = userService.getById(currentUser.getId());
//        String avatar = user.getAvatar();
//
//        //如果头像id为空就返回默认的
//        if (ToolUtil.isEmpty(avatar)) {
//            avatar = DefaultAvatar.BASE_64_AVATAR;
//        } else {
//            FileInfo fileInfo = fileInfoService.getById(avatar);
//            if (fileInfo == null) {
//                avatar = DefaultAvatar.BASE_64_AVATAR;
//            } else {
//                avatar = fileInfo.getFileData();
//            }
//        }
//
//        //输出图片的文件流
//        try {
//            response.setContentType("image/jpeg");
//            byte[] decode = Base64.decode(avatar);
//            response.getOutputStream().write(decode);
//        } catch (IOException e) {
//            System.out.println("获取图片的流错误！" + avatar);
//            throw new ServiceException(CoreExceptionEnum.SERVICE_ERROR);
//        }
//
//        return null;
//    }
//
//    /**
//     * 获取当前用户详情
//     *
//     * @author fengshuonan
//     * @Date 2018/12/23 6:59 PM
//     */
//    @RequestMapping("/currentUserInfo")
//    @ResponseBody
//    public ResponseData getUserInfo() {
//
//        ShiroUser currentUser = ShiroKit.getUser();
//        if (currentUser == null) {
//            throw new ServiceException(CoreExceptionEnum.NO_CURRENT_USER);
//        }
//
//        User user = userService.getById(currentUser.getId());
//        Map<String, Object> map = UserFactory.removeUnSafeFields(user);
//
//        HashMap<Object, Object> hashMap = CollectionUtil.newHashMap();
//        hashMap.putAll(map);
//        hashMap.put("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));
//        hashMap.put("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));
//
//        return ResponseData.success(hashMap);
//    }
//
//    /**
//     * layui上传组件 通用文件上传接口
//     *
//     * @author fengshuonan
//     * @Date 2019-2-23 10:48:29
//     */
//    @RequestMapping(method = RequestMethod.POST, path = "/upload")
//    @ResponseBody
//    public ResponseData layuiUpload(@RequestPart("file") MultipartFile picture) {
//
//        String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
//        try {
//            String fileSavePath = luProperties.getFileUploadPath();
//            picture.transferTo(new File(fileSavePath + pictureName));
//        } catch (Exception e) {
//            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
//        }
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("fileId", IdWorker.getIdStr());
//        return ResponseData.success(0, "上传成功", map);
//    }


}
